const Service = require('egg').Service
const jwt = require('jsonwebtoken')

class UserSerive extends Service {
  // 获取user表
  get User () {
    return this.ctx.model.User
  }

  // 查找用户名
  findByUsername(condition) {
    return this.User.findOne(condition).select('+password')
  }

  // 生成token
  createToken (data) {
    const token = jwt.sign(data, this.app.config.jwt.secret, {
      expiresIn: this.app.config.jwt.expiresIn
    })
    return token
  }

  // 解析token 
  verifyToken (token) {
    return jwt.verify(token, this.app.config.jwt.secret)
  }
  
  // 注册
  async register(data) {
    data.password = this.ctx.helper.md5(data.password)
    const _random = Math.ceil( Math.random() *  10 ) + 1
    data.avatar = '/public/images/avatars/avatar'+_random+'.jpg'
    const _user = new this.User(data)
    await _user.save()
    return _user
  }

  // 修改密码
  async updatePassword(body) {
    const newPassword = this.ctx.helper.md5(body.password)
    return await this.User.updateOne({
      id: '61931d7661e50239a429095e'
    },{
      $set: {
        password: newPassword
      }
    })
  }
}

module.exports = UserSerive